// 全局变量
let uploadedFiles = new Map(); // 存储上传的文件信息
let pdfPages = []; // PDF页面结构配置
let selectedSourcePage = null; // 当前选中的源页面
let selectedCanvasElement = null; // 当前选中的画布元素
let currentPdfPage = null; // 当前活动的PDF页面
let draggedElement = null; // 当前拖拽的元素

// 画布缩放常量 - 1mm对应多少像素
const BASE_CANVAS_SCALE = 2.5; // A4纸(210×297mm)基础显示为(525×742px)
let canvasZoomLevel = 100; // 当前缩放级别（百分比）
let allowOverlap = true; // 是否允许PDF元素重叠

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeEventListeners();
    updatePdfPagesDisplay();
    updatePageCountDisplay();
    showCanvasEmptyState();
    updateZoomDisplay();
});

// 切换标签页
function switchTab(tabName) {
    // 移除所有标签按钮的active类
    const tabButtons = document.querySelectorAll('.tab-btn');
    tabButtons.forEach(btn => btn.classList.remove('active'));
    
    // 隐藏所有标签页内容
    const tabPanels = document.querySelectorAll('.tab-panel');
    tabPanels.forEach(panel => panel.classList.remove('active'));
    
    // 激活选中的标签
    const activeTabBtn = event.target;
    activeTabBtn.classList.add('active');
    
    // 显示对应的标签页内容
    let targetPanelId = '';
    switch(tabName) {
        case 'pageList':
            targetPanelId = 'pageListTab';
            break;
        case 'pageSettings':
            targetPanelId = 'pageSettingsTab';
            break;
        case 'elementSettings':
            targetPanelId = 'elementSettingsTab';
            break;
    }
    
    const targetPanel = document.getElementById(targetPanelId);
    if (targetPanel) {
        targetPanel.classList.add('active');
    }
}

// 初始化事件监听器
function initializeEventListeners() {
    const uploadArea = document.getElementById('uploadArea');
    const fileInput = document.getElementById('fileInput');
    const uploadButton = uploadArea.querySelector('.btn');
    
    // 文件上传相关事件
    uploadButton.addEventListener('click', (e) => {
        e.stopPropagation();
        fileInput.click();
    });
    uploadArea.addEventListener('click', () => fileInput.click());
    uploadArea.addEventListener('dragover', handleDragOver);
    uploadArea.addEventListener('dragleave', handleDragLeave);
    uploadArea.addEventListener('drop', handleDrop);
    fileInput.addEventListener('change', handleFileSelect);
    
    // 模态框关闭事件
    window.addEventListener('click', function(event) {
        const modal = document.getElementById('pageConfigModal');
        if (event.target === modal) {
            closeModal();
        }
    });
}

// 处理拖拽悬停
function handleDragOver(e) {
    e.preventDefault();
    e.currentTarget.classList.add('dragover');
}

// 处理拖拽离开
function handleDragLeave(e) {
    e.preventDefault();
    e.currentTarget.classList.remove('dragover');
}

// 处理文件拖拽放下
function handleDrop(e) {
    e.preventDefault();
    e.currentTarget.classList.remove('dragover');
    const files = Array.from(e.dataTransfer.files).filter(file => file.type === 'application/pdf');
    if (files.length > 0) {
        uploadFiles(files);
    } else {
        showMessage('请选择PDF文件', 'error');
    }
}

// 处理文件选择
function handleFileSelect(e) {
    const files = Array.from(e.target.files);
    uploadFiles(files);
    e.target.value = ''; // 清空input，允许重复选择同一文件
}

// 上传文件
async function uploadFiles(files) {
    showLoading(true);
    
    for (const file of files) {
        try {
            const formData = new FormData();
            formData.append('file', file);
            
            const response = await fetch('/api/pdf/upload', {
                method: 'POST',
                body: formData
            });
            
            const result = await response.json();
            
            if (result.success) {
                uploadedFiles.set(result.data[0].fileId, {
                    fileName: file.name,
                    pages: result.data
                });
                updateUploadedFilesDisplay();
                updateSourcePagesDisplay();
                showMessage(`文件 ${file.name} 上传成功`, 'success');
            } else {
                showMessage(`上传失败: ${result.message}`, 'error');
            }
        } catch (error) {
            console.error('上传文件失败:', error);
            showMessage(`上传文件 ${file.name} 失败`, 'error');
        }
    }
    
    showLoading(false);
}

// 更新已上传文件显示
function updateUploadedFilesDisplay() {
    const container = document.getElementById('uploadedFilesList');
    
    if (uploadedFiles.size === 0) {
        container.innerHTML = '';
        return;
    }
    
    let html = '';
    uploadedFiles.forEach((fileData, fileId) => {
        html += `
            <div class="file-item">
                <div>
                    <div class="file-name">${fileData.fileName}</div>
                    <div class="file-info">共 ${fileData.pages.length} 页</div>
                </div>
                <button class="btn btn-danger btn-sm" onclick="removeFile('${fileId}')">×</button>
            </div>
        `;
    });
    
    container.innerHTML = html;
}

// 更新源页面显示
function updateSourcePagesDisplay() {
    const container = document.getElementById('sourcePages');
    
    if (uploadedFiles.size === 0) {
        container.innerHTML = `
            <div class="empty-state">
                <p>上传PDF文件后，页面缩略图将显示在此处</p>
            </div>
        `;
        return;
    }
    
    let html = '';
    uploadedFiles.forEach((fileData, fileId) => {
        fileData.pages.forEach(page => {
            html += `
                <div class="page-item" onclick="selectSourcePage('${fileId}', ${page.pageIndex})" 
                     draggable="true" ondragstart="handleSourcePageDragStart(event, '${fileId}', ${page.pageIndex})">
                    <img src="data:image/png;base64,${page.thumbnailBase64}" 
                         alt="Page ${page.pageIndex + 1}" class="page-thumbnail">
                    <div class="page-info">
                        <div><strong>${page.fileName}</strong></div>
                        <div>第 ${page.pageIndex + 1} 页</div>
                        <div>${Math.round(page.widthMm)}×${Math.round(page.heightMm)}mm</div>
                        <div>旋转: ${page.rotation}°</div>
                    </div>
                </div>
            `;
        });
    });
    
    container.innerHTML = html;
}

// 显示画布空状态
function showCanvasEmptyState() {
    const canvasArea = document.getElementById('canvasArea');
    const emptyState = canvasArea.querySelector('.canvas-empty-state');
    const canvasPages = canvasArea.querySelector('.canvas-pages');
    
    if (!currentPdfPage) {
        emptyState.style.display = 'block';
        canvasPages.style.display = 'none';
        emptyState.querySelector('h4').textContent = '选择PDF页面开始设计';
        emptyState.querySelector('p').innerHTML = `
            <p>1. 在右侧添加PDF页面</p>
            <p>2. 点击页面进入编辑模式</p>
            <p>3. 从左侧拖拽内容到画布</p>
        `;
    } else {
        emptyState.style.display = 'none';
        canvasPages.style.display = 'block';
    }
}

// 添加PDF页面
function addPdfPage() {
    const pageId = 'pdf-page-' + Date.now();
    const pdfPage = {
        id: pageId,
        widthMm: 210,
        heightMm: 297,
        elements: []
    };
    
    pdfPages.push(pdfPage);
    updatePdfPagesDisplay();
    updatePageCountDisplay();
    selectPdfPage(pageId);
}

// 更新PDF页面显示
function updatePdfPagesDisplay() {
    const container = document.getElementById('pdfPagesList');
    
    if (pdfPages.length === 0) {
        container.innerHTML = `
            <div class="empty-state">
                <p>点击"+ 添加页面"开始创建PDF结构</p>
            </div>
        `;
        return;
    }
    
    let html = '';
    pdfPages.forEach((page, index) => {
        const isActive = currentPdfPage && currentPdfPage.id === page.id;
        html += `
            <div class="pdf-page-item ${isActive ? 'active' : ''}" onclick="selectPdfPage('${page.id}')">
                <div class="pdf-page-thumbnail">
                    第${index + 1}页
                </div>
                <div class="pdf-page-info">
                    <div class="pdf-page-title">页面 ${index + 1}</div>
                    <div class="pdf-page-size">${Math.round(page.widthMm)}×${Math.round(page.heightMm)}mm</div>
                    <div class="pdf-page-size">${page.elements.length} 个元素</div>
                </div>
                <div class="pdf-page-controls">
                    <button class="btn btn-danger btn-sm" onclick="removePdfPage('${page.id}', event)">×</button>
                </div>
            </div>
        `;
    });
    
    container.innerHTML = html;
}

// 选择PDF页面
function selectPdfPage(pageId) {
    const page = pdfPages.find(p => p.id === pageId);
    if (!page) return;
    
    currentPdfPage = page;
    selectedCanvasElement = null;
    
    updatePdfPagesDisplay();
    updateCanvasDisplay();
    updateCurrentPageSettings();
}

// 更新当前页面设置
function updateCurrentPageSettings() {
    const currentPageInfo = document.getElementById('currentPageInfo');
    const sizeControls = document.getElementById('sizeControls');
    const widthInput = document.getElementById('currentPageWidth');
    const heightInput = document.getElementById('currentPageHeight');
    const elementSettings = document.getElementById('elementSettings');
    
    if (currentPdfPage) {
        const pageIndex = pdfPages.findIndex(p => p.id === currentPdfPage.id) + 1;
        currentPageInfo.innerHTML = `
            <strong>页面 ${pageIndex}</strong><br>
            尺寸: ${Math.round(currentPdfPage.widthMm)}×${Math.round(currentPdfPage.heightMm)}mm<br>
            元素数量: ${currentPdfPage.elements.length}
        `;
        sizeControls.style.display = 'block';
        widthInput.value = Math.round(currentPdfPage.widthMm);
        heightInput.value = Math.round(currentPdfPage.heightMm);
    } else {
        currentPageInfo.innerHTML = '<p class="no-selection">请选择一个PDF页面</p>';
        sizeControls.style.display = 'none';
    }
    
    // 更新元素设置
    if (selectedCanvasElement && currentPdfPage) {
        const element = currentPdfPage.elements[selectedCanvasElement.elementIndex];
        
        // 获取源页面尺寸用于尺寸输入
        const fileData = uploadedFiles.get(element.sourceFileId);
        const sourcePageData = fileData?.pages[element.sourcePageIndex];
        const originalWidth = sourcePageData?.widthMm || 0;
        const originalHeight = sourcePageData?.heightMm || 0;
        
        // 计算裁切后的尺寸
        const cropLeft = element.transform.cropLeft || 0;
        const cropRight = element.transform.cropRight || 0;
        const cropTop = element.transform.cropTop || 0;
        const cropBottom = element.transform.cropBottom || 0;
        
        const croppedWidth = Math.max(0, originalWidth - cropLeft - cropRight);
        const croppedHeight = Math.max(0, originalHeight - cropTop - cropBottom);
        
        // 显示当前实际尺寸（裁切后应用缩放）
        const currentWidth = Math.round(croppedWidth * element.transform.scaleX * 10) / 10;
        const currentHeight = Math.round(croppedHeight * element.transform.scaleY * 10) / 10;
        
        // 初始化裁切属性（如果不存在）
        if (!element.transform.cropTop) element.transform.cropTop = 0;
        if (!element.transform.cropBottom) element.transform.cropBottom = 0;
        if (!element.transform.cropLeft) element.transform.cropLeft = 0;
        if (!element.transform.cropRight) element.transform.cropRight = 0;
        
        elementSettings.innerHTML = `
            <div style="margin-bottom: 15px;">
                <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #495057;">位置 (mm):</label>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px;">
                    <div>
                        <label style="font-size: 0.8em; color: #666; display: block; margin-bottom: 3px;">X坐标</label>
                        <input type="number" value="${Math.round(element.transform.offsetX * 10) / 10}" step="0.1" 
                               onchange="updateElementTransform('offsetX', this.value)" 
                               style="width: 100%; padding: 6px 8px; border: 1px solid #ced4da; border-radius: 4px; font-size: 0.9em;">
                    </div>
                    <div>
                        <label style="font-size: 0.8em; color: #666; display: block; margin-bottom: 3px;">Y坐标</label>
                        <input type="number" value="${Math.round(element.transform.offsetY * 10) / 10}" step="0.1" 
                               onchange="updateElementTransform('offsetY', this.value)" 
                               style="width: 100%; padding: 6px 8px; border: 1px solid #ced4da; border-radius: 4px; font-size: 0.9em;">
                    </div>
                </div>
            </div>
            <div style="margin-bottom: 15px;">
                <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #495057;">尺寸 (mm):</label>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px;">
                    <div>
                        <label style="font-size: 0.8em; color: #666; display: block; margin-bottom: 3px;">宽度</label>
                        <input type="number" value="${currentWidth}" step="0.1" min="1"
                               onchange="updateElementSize('width', this.value)" 
                               style="width: 100%; padding: 6px 8px; border: 1px solid #ced4da; border-radius: 4px; font-size: 0.9em;">
                    </div>
                    <div>
                        <label style="font-size: 0.8em; color: #666; display: block; margin-bottom: 3px;">高度</label>
                        <input type="number" value="${currentHeight}" step="0.1" min="1"
                               onchange="updateElementSize('height', this.value)" 
                               style="width: 100%; padding: 6px 8px; border: 1px solid #ced4da; border-radius: 4px; font-size: 0.9em;">
                    </div>
                </div>
                <small style="color: #666; font-size: 0.75em; margin-top: 5px; display: block;">原始: ${Math.round(originalWidth * 10) / 10}×${Math.round(originalHeight * 10) / 10}mm</small>
            </div>
            <div style="margin-bottom: 15px;">
                <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #495057;">旋转角度:</label>
                <div>
                    <label style="font-size: 0.8em; color: #666; display: block; margin-bottom: 3px;">角度 (度)</label>
                    <input type="number" value="${Math.round(element.transform.rotation)}" step="1" min="-360" max="360"
                           onchange="updateElementTransform('rotation', this.value)" 
                           style="width: 100%; padding: 6px 8px; border: 1px solid #ced4da; border-radius: 4px; font-size: 0.9em;">
                </div>
            </div>
            <div style="margin-bottom: 15px;">
                <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #495057;">裁切边距 (mm):</label>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px;">
                    <div>
                        <label style="font-size: 0.8em; color: #666; display: block; margin-bottom: 3px;">上边距</label>
                        <input type="number" value="${Math.round(element.transform.cropTop * 10) / 10}" step="0.1" min="0"
                               onchange="updateElementTransform('cropTop', this.value)" 
                               style="width: 100%; padding: 6px 8px; border: 1px solid #ced4da; border-radius: 4px; font-size: 0.9em;">
                    </div>
                    <div>
                        <label style="font-size: 0.8em; color: #666; display: block; margin-bottom: 3px;">下边距</label>
                        <input type="number" value="${Math.round(element.transform.cropBottom * 10) / 10}" step="0.1" min="0"
                               onchange="updateElementTransform('cropBottom', this.value)" 
                               style="width: 100%; padding: 6px 8px; border: 1px solid #ced4da; border-radius: 4px; font-size: 0.9em;">
                    </div>
                    <div>
                        <label style="font-size: 0.8em; color: #666; display: block; margin-bottom: 3px;">左边距</label>
                        <input type="number" value="${Math.round(element.transform.cropLeft * 10) / 10}" step="0.1" min="0"
                               onchange="updateElementTransform('cropLeft', this.value)" 
                               style="width: 100%; padding: 6px 8px; border: 1px solid #ced4da; border-radius: 4px; font-size: 0.9em;">
                    </div>
                    <div>
                        <label style="font-size: 0.8em; color: #666; display: block; margin-bottom: 3px;">右边距</label>
                        <input type="number" value="${Math.round(element.transform.cropRight * 10) / 10}" step="0.1" min="0"
                               onchange="updateElementTransform('cropRight', this.value)" 
                               style="width: 100%; padding: 6px 8px; border: 1px solid #ced4da; border-radius: 4px; font-size: 0.9em;">
                    </div>
                </div>
            </div>
            <button class="btn btn-danger btn-sm" onclick="removeSelectedElement()" 
                    style="width: 100%; margin-top: 10px; padding: 8px 16px;">
                <span>🗑️</span> 删除元素
            </button>
        `;
    } else {
        elementSettings.innerHTML = '<p class="no-selection">请选择画布中的元素</p>';
    }
}

// 更新页数显示
function updatePageCountDisplay() {
    document.getElementById('pageCountDisplay').textContent = pdfPages.length;
}

// 调整缩放级别
function adjustZoom(delta) {
    canvasZoomLevel = Math.max(10, Math.min(200, canvasZoomLevel + delta));
    updateZoomDisplay();
    updateCanvasDisplay();
}

// 重置缩放
function resetZoom() {
    canvasZoomLevel = 100;
    updateZoomDisplay();
    updateCanvasDisplay();
}

// 更新缩放显示
function updateZoomDisplay() {
    const zoomDisplay = document.getElementById('zoomDisplay');
    if (zoomDisplay) {
        zoomDisplay.textContent = canvasZoomLevel + '%';
    }
}

// 获取当前的画布缩放比例
function getCanvasScale() {
    return BASE_CANVAS_SCALE * (canvasZoomLevel / 100);
}

// 切换重叠模式
function toggleOverlapMode() {
    allowOverlap = document.getElementById('allowOverlap').checked;
    showMessage(allowOverlap ? '已启用PDF重叠模式' : '已禁用PDF重叠模式', 'info');
}

// 检测元素是否与其他元素重叠
function checkElementOverlap(elementIndex, newX, newY, newWidth, newHeight, rotation = 0) {
    if (!currentPdfPage || allowOverlap) return false;
    
    // 获取当前元素的边界框（考虑旋转）
    const newBounds = getElementBounds(newX, newY, newWidth, newHeight, rotation);
    
    // 检查与其他元素的重叠
    for (let i = 0; i < currentPdfPage.elements.length; i++) {
        if (i === elementIndex) continue; // 跳过自己
        
        const otherElement = currentPdfPage.elements[i];
        const fileData = uploadedFiles.get(otherElement.sourceFileId);
        const sourcePageData = fileData?.pages[otherElement.sourcePageIndex];
        
        if (!sourcePageData) continue;
        
        // 计算其他元素的实际尺寸
        const cropLeft = otherElement.transform.cropLeft || 0;
        const cropRight = otherElement.transform.cropRight || 0;
        const cropTop = otherElement.transform.cropTop || 0;
        const cropBottom = otherElement.transform.cropBottom || 0;
        
        const otherCroppedWidth = Math.max(0, sourcePageData.widthMm - cropLeft - cropRight);
        const otherCroppedHeight = Math.max(0, sourcePageData.heightMm - cropTop - cropBottom);
        
        const otherWidth = otherCroppedWidth * otherElement.transform.scaleX;
        const otherHeight = otherCroppedHeight * otherElement.transform.scaleY;
        
        // 获取其他元素的边界框
        const otherBounds = getElementBounds(
            otherElement.transform.offsetX,
            otherElement.transform.offsetY,
            otherWidth,
            otherHeight,
            otherElement.transform.rotation
        );
        
        // 检查边界框是否重叠
        if (boundsOverlap(newBounds, otherBounds)) {
            return true;
        }
    }
    
    return false;
}

// 获取元素的边界框（考虑旋转）
function getElementBounds(x, y, width, height, rotation) {
    const centerX = x + width / 2;
    const centerY = y + height / 2;
    const rad = (rotation * Math.PI) / 180;
    
    // 计算旋转后的四个角点
    const corners = [
        { x: -width / 2, y: -height / 2 },
        { x: width / 2, y: -height / 2 },
        { x: width / 2, y: height / 2 },
        { x: -width / 2, y: height / 2 }
    ];
    
    const rotatedCorners = corners.map(corner => ({
        x: centerX + corner.x * Math.cos(rad) - corner.y * Math.sin(rad),
        y: centerY + corner.x * Math.sin(rad) + corner.y * Math.cos(rad)
    }));
    
    // 找出边界框
    const xs = rotatedCorners.map(p => p.x);
    const ys = rotatedCorners.map(p => p.y);
    
    return {
        minX: Math.min(...xs),
        maxX: Math.max(...xs),
        minY: Math.min(...ys),
        maxY: Math.max(...ys)
    };
}

// 检查两个边界框是否重叠
function boundsOverlap(bounds1, bounds2) {
    return !(bounds1.maxX <= bounds2.minX || 
             bounds2.maxX <= bounds1.minX || 
             bounds1.maxY <= bounds2.minY || 
             bounds2.maxY <= bounds1.minY);
}

// 寻找无重叠的位置
function findNonOverlappingPosition(elementIndex, preferredX, preferredY, width, height, rotation = 0) {
    if (allowOverlap) {
        return { x: preferredX, y: preferredY };
    }
    
    // 如果首选位置不重叠，直接返回
    if (!checkElementOverlap(elementIndex, preferredX, preferredY, width, height, rotation)) {
        return { x: preferredX, y: preferredY };
    }
    
    // 尝试在首选位置周围寻找无重叠的位置
    const step = 5; // 5mm步长
    const maxOffset = 50; // 最大偏移50mm
    
    for (let offset = step; offset <= maxOffset; offset += step) {
        // 尝试8个方向
        const directions = [
            { x: offset, y: 0 },      // 右
            { x: -offset, y: 0 },     // 左
            { x: 0, y: offset },      // 下
            { x: 0, y: -offset },     // 上
            { x: offset, y: offset }, // 右下
            { x: -offset, y: offset }, // 左下
            { x: offset, y: -offset }, // 右上
            { x: -offset, y: -offset } // 左上
        ];
        
        for (const dir of directions) {
            const newX = preferredX + dir.x;
            const newY = preferredY + dir.y;
            
            // 确保不超出页面边界
            if (newX >= 0 && newY >= 0 && 
                newX + width <= currentPdfPage.widthMm && 
                newY + height <= currentPdfPage.heightMm) {
                
                if (!checkElementOverlap(elementIndex, newX, newY, width, height, rotation)) {
                    return { x: newX, y: newY };
                }
            }
        }
    }
    
    // 如果找不到合适位置，返回首选位置（用户需要手动调整）
    return { x: preferredX, y: preferredY };
}

// 调整页数
function adjustPageCount(delta) {
    if (delta > 0) {
        addPdfPage();
    } else if (delta < 0 && pdfPages.length > 0) {
        const lastPage = pdfPages[pdfPages.length - 1];
        removePdfPage(lastPage.id);
    }
}

// 删除PDF页面
function removePdfPage(pageId, event) {
    if (event) {
        event.stopPropagation();
    }
    
    if (pdfPages.length <= 1) {
        showMessage('至少需要保留一个页面', 'warning');
        return;
    }
    
    if (confirm('确定要删除这个页面吗？')) {
        const pageIndex = pdfPages.findIndex(p => p.id === pageId);
        pdfPages = pdfPages.filter(p => p.id !== pageId);
        
        // 如果删除的是当前页面，选择相邻页面
        if (currentPdfPage && currentPdfPage.id === pageId) {
            if (pdfPages.length > 0) {
                const newIndex = Math.min(pageIndex, pdfPages.length - 1);
                currentPdfPage = pdfPages[newIndex];
            } else {
                currentPdfPage = null;
            }
        }
        
        updatePdfPagesDisplay();
        updatePageCountDisplay();
        updateCanvasDisplay();
        updateCurrentPageSettings();
    }
}

// 设置当前页面尺寸
function setCurrentPageSize(width, height) {
    document.getElementById('currentPageWidth').value = width;
    document.getElementById('currentPageHeight').value = height;
    // 自动应用尺寸
    applyCurrentPageSize();
}

// 应用当前页面尺寸
function applyCurrentPageSize() {
    if (!currentPdfPage) return;
    
    const widthInput = document.getElementById('currentPageWidth');
    const heightInput = document.getElementById('currentPageHeight');
    
    let width = parseFloat(widthInput.value);
    let height = parseFloat(heightInput.value);
    
    // 验证尺寸范围
    if (isNaN(width) || width < 10) {
        width = 210;
        widthInput.value = width;
    }
    if (isNaN(height) || height < 10) {
        height = 297;
        heightInput.value = height;
    }
    
    // 限制最大尺寸
    if (width > 2000) {
        width = 2000;
        widthInput.value = width;
    }
    if (height > 2000) {
        height = 2000;
        heightInput.value = height;
    }
    
    // 应用新尺寸
    currentPdfPage.widthMm = width;
    currentPdfPage.heightMm = height;
    
    updatePdfPagesDisplay();
    updateCanvasDisplay();
    updateCurrentPageSettings();
    
    // 显示成功消息（避免过于频繁）
    if (window.sizeUpdateTimeout) {
        clearTimeout(window.sizeUpdateTimeout);
    }
    window.sizeUpdateTimeout = setTimeout(() => {
        showMessage(`页面尺寸已更新为 ${Math.round(width)}×${Math.round(height)}mm`, 'success');
    }, 500);
}

// 添加画布页面
function addCanvasPage() {
    const pageId = 'canvas-page-' + Date.now();
    const canvasPage = {
        id: pageId,
        widthMm: 210,
        heightMm: 297,
        elements: []
    };
    
    canvasPages.push(canvasPage);
    updateCanvasDisplay();
    setCurrentCanvasPage(pageId);
}

// 更新画布显示
function updateCanvasDisplay() {
    const canvasContainer = document.getElementById('canvasPages');
    
    if (!currentPdfPage) {
        showCanvasEmptyState();
        return;
    }
    
    const pageIndex = pdfPages.findIndex(p => p.id === currentPdfPage.id) + 1;
    // 使用当前缩放级别计算画布尺寸
    const currentScale = getCanvasScale();
    const canvasWidth = currentPdfPage.widthMm * currentScale;
    const canvasHeight = currentPdfPage.heightMm * currentScale;
    
    const html = `
        <div class="canvas-page-container">
            <div class="canvas-page active" id="${currentPdfPage.id}">
                <div class="canvas-page-header">
                    <span class="canvas-page-title">PDF 第${pageIndex}页 (${Math.round(currentPdfPage.widthMm)}×${Math.round(currentPdfPage.heightMm)}mm)</span>
                    <div class="canvas-page-indicator">当前编辑</div>
                </div>
                <div class="canvas-page-content" 
                     style="height: ${canvasHeight}px; width: ${canvasWidth}px;"
                     ondrop="handleCanvasPageDrop(event, '${currentPdfPage.id}')" 
                     ondragover="handleCanvasPageDragOver(event)"
                     ondragleave="handleCanvasPageDragLeave(event)"
                     onclick="clearElementSelection()">
                    ${renderCanvasPageElements(currentPdfPage)}
                    <div class="canvas-page-drop-zone ${currentPdfPage.elements.length > 0 ? 'has-elements' : ''}">
                        ${currentPdfPage.elements.length === 0 ? '拖拽左侧页面到此处' : ''}
                    </div>
                </div>
            </div>
        </div>
    `;
    
    canvasContainer.innerHTML = html;
    showCanvasEmptyState();
}

// 处理画布页面拖拽离开
function handleCanvasPageDragLeave(event) {
    const dropZone = event.currentTarget.querySelector('.canvas-page-drop-zone');
    if (dropZone) {
        dropZone.classList.remove('drag-over');
    }
}

// 渲染画布页面元素
function renderCanvasPageElements(page) {
    const currentScale = getCanvasScale();
    return page.elements.map((element, index) => {
        const fileData = uploadedFiles.get(element.sourceFileId);
        if (!fileData) return '';
        
        const pageData = fileData.pages[element.sourcePageIndex];
        if (!pageData) return '';
        
        // 计算裁切后的实际尺寸
        const cropLeft = element.transform.cropLeft || 0;
        const cropRight = element.transform.cropRight || 0;
        const cropTop = element.transform.cropTop || 0;
        const cropBottom = element.transform.cropBottom || 0;
        
        const croppedWidth = Math.max(0, pageData.widthMm - cropLeft - cropRight);
        const croppedHeight = Math.max(0, pageData.heightMm - cropTop - cropBottom);
        
        const displayWidth = croppedWidth * element.transform.scaleX * currentScale;
        const displayHeight = croppedHeight * element.transform.scaleY * currentScale;
        
        const isSelected = selectedCanvasElement && selectedCanvasElement.elementIndex === index;
        
        // 计算图片的缩放和裁切
        // 如果有裁切，需要计算图片显示的偏移和缩放
        const hasCrop = cropLeft > 0 || cropRight > 0 || cropTop > 0 || cropBottom > 0;
        let imgStyle = '';
        
        if (hasCrop) {
            // 计算裁切百分比
            const cropLeftPercent = (cropLeft / pageData.widthMm) * 100;
            const cropTopPercent = (cropTop / pageData.heightMm) * 100;
            const cropWidthPercent = (croppedWidth / pageData.widthMm) * 100;
            const cropHeightPercent = (croppedHeight / pageData.heightMm) * 100;
            
            // 使用object-fit: none并调整object-position来实现裁切效果
            // 图片需要缩放到容器的适当大小
            const imgWidth = (pageData.widthMm / croppedWidth) * 100;
            const imgHeight = (pageData.heightMm / croppedHeight) * 100;
            const imgLeft = -(cropLeft / croppedWidth) * 100;
            const imgTop = -(cropTop / croppedHeight) * 100;
            
            imgStyle = `width: ${imgWidth}%; 
                       height: ${imgHeight}%; 
                       object-fit: fill;
                       position: relative;
                       left: ${imgLeft}%;
                       top: ${imgTop}%;
                       pointer-events: none;`;
        } else {
            // 没有裁切，使用fill让图片完全填充
            imgStyle = `width: 100%; 
                       height: 100%; 
                       object-fit: fill;
                       pointer-events: none;`;
        }
        
        return `
            <div class="canvas-element ${isSelected ? 'selected' : ''}" 
                 style="left: ${element.transform.offsetX * currentScale}px; 
                        top: ${element.transform.offsetY * currentScale}px; 
                        width: ${displayWidth}px; 
                        height: ${displayHeight}px;
                        transform: rotate(${element.transform.rotation}deg);
                        position: absolute;
                        cursor: move;
                        overflow: hidden;"
                 onclick="selectCanvasElement(${index})"
                 onmousedown="startDragElement(event, ${index})"
                 draggable="false">
                <img src="data:image/png;base64,${pageData.thumbnailBase64}" alt="Element" 
                     style="${imgStyle}">
                ${isSelected ? '<div class="element-resize-handles"></div>' : ''}
            </div>
        `;
    }).join('');
}

// 设置当前画布页面
function setCurrentCanvasPage(pageId) {
    const page = canvasPages.find(p => p.id === pageId);
    if (!page) return;
    
    currentCanvasPage = page;
    selectedCanvasElement = null;
    updateCanvasDisplay();
    updatePageSettings();
}

// 更新页面设置面板
function updatePageSettings() {
    const widthInput = document.getElementById('canvasWidth');
    const heightInput = document.getElementById('canvasHeight');
    const elementSettings = document.getElementById('elementSettings');
    
    if (currentCanvasPage) {
        widthInput.value = Math.round(currentCanvasPage.widthMm);
        heightInput.value = Math.round(currentCanvasPage.heightMm);
    }
    
    if (selectedCanvasElement) {
        const element = currentCanvasPage.elements[selectedCanvasElement.elementIndex];
        elementSettings.innerHTML = `
            <div style="margin-bottom: 10px;">
                <label>位置 (mm):</label>
                <div style="display: flex; gap: 5px; margin-top: 5px;">
                    <input type="number" value="${element.transform.offsetX}" step="0.1" 
                           onchange="updateElementTransform('offsetX', this.value)" placeholder="X">
                    <input type="number" value="${element.transform.offsetY}" step="0.1" 
                           onchange="updateElementTransform('offsetY', this.value)" placeholder="Y">
                </div>
            </div>
            <div style="margin-bottom: 10px;">
                <label>缩放:</label>
                <div style="display: flex; gap: 5px; margin-top: 5px;">
                    <input type="number" value="${element.transform.scaleX}" step="0.01" min="0.1" max="5"
                           onchange="updateElementTransform('scaleX', this.value)" placeholder="X缩放">
                    <input type="number" value="${element.transform.scaleY}" step="0.01" min="0.1" max="5"
                           onchange="updateElementTransform('scaleY', this.value)" placeholder="Y缩放">
                </div>
            </div>
            <div style="margin-bottom: 10px;">
                <label>旋转 (度):</label>
                <input type="number" value="${element.transform.rotation}" step="1" min="-360" max="360"
                       onchange="updateElementTransform('rotation', this.value)" placeholder="角度"
                       style="width: 100%; margin-top: 5px;">
            </div>
            <button class="btn btn-danger btn-sm btn-block" onclick="removeSelectedElement()">删除元素</button>
        `;
    } else {
        elementSettings.innerHTML = '<p class="no-selection">请选择画布中的元素</p>';
    }
}

// 选择源页面
function selectSourcePage(fileId, pageIndex) {
    // 移除之前的选中状态
    document.querySelectorAll('.page-item').forEach(item => {
        item.classList.remove('selected');
    });
    
    // 添加选中状态
    event.currentTarget.classList.add('selected');
    
    selectedSourcePage = { fileId, pageIndex };
}

// 处理源页面拖拽开始
function handleSourcePageDragStart(event, fileId, pageIndex) {
    console.log('开始拖拽源页面:', fileId, pageIndex); // 调试信息
    const dragData = {
        fileId: fileId,
        pageIndex: pageIndex
    };
    event.dataTransfer.setData('application/json', JSON.stringify(dragData));
    event.dataTransfer.effectAllowed = 'copy';
    event.currentTarget.classList.add('dragging');
}

// 添加目标页面 (兼容旧版本调用)
function addTargetPage() {
    addPdfPage();
}

// 添加画布页面 (兼容旧版本调用)
function addCanvasPage() {
    addPdfPage();
}

// 更新目标页面显示
function updateTargetPagesDisplay() {
    const container = document.getElementById('targetPages');
    
    if (targetPages.length === 0) {
        container.innerHTML = '<p class="empty-message">点击"添加目标页面"开始配置</p>';
        return;
    }
    
    let html = '';
    targetPages.forEach((targetPage, index) => {
        html += `
            <div class="target-page" id="${targetPage.id}">
                <div class="target-page-header">
                    <span class="target-page-title">目标页面 ${index + 1}</span>
                    <div>
                        <button class="btn btn-sm btn-primary" onclick="configTargetPage('${targetPage.id}')">配置</button>
                        <button class="btn btn-sm btn-danger" onclick="removeTargetPage('${targetPage.id}')">删除</button>
                    </div>
                </div>
                <div class="target-page-content">
                    <div class="target-page-config">
                        <div class="config-item">
                            <label>页面尺寸:</label>
                            <div>${Math.round(targetPage.widthMm)} × ${Math.round(targetPage.heightMm)} mm</div>
                        </div>
                        <div class="config-item">
                            <label>包含页面:</label>
                            <div>${targetPage.sourcePages.length} 个源页面</div>
                        </div>
                    </div>
                    <div class="source-pages-list" 
                         ondragover="handleTargetDragOver(event)" 
                         ondrop="handleTargetDrop(event, '${targetPage.id}')"
                         ondragleave="handleTargetDragLeave(event)">
                        ${renderTargetSourcePages(targetPage.sourcePages)}
                    </div>
                </div>
            </div>
        `;
    });
    
    container.innerHTML = html;
}

// 渲染目标页面中的源页面
function renderTargetSourcePages(sourcePages) {
    if (sourcePages.length === 0) {
        return '<p style="text-align: center; color: #666; margin: 20px;">拖拽源页面到此处</p>';
    }
    
    return sourcePages.map((sourcePage, index) => {
        const fileData = uploadedFiles.get(sourcePage.sourceFileId);
        const pageData = fileData.pages[sourcePage.sourcePageIndex];
        
        return `
            <div class="source-page-item">
                <img src="data:image/png;base64,${pageData.thumbnailBase64}" 
                     alt="Source page" class="source-page-thumbnail">
                <div class="source-page-info">
                    <div><strong>${pageData.fileName}</strong> - 第${pageData.pageIndex + 1}页</div>
                    <div>位置: (${sourcePage.transform.offsetX}, ${sourcePage.transform.offsetY})</div>
                    <div>缩放: ${sourcePage.transform.scaleX} × ${sourcePage.transform.scaleY}</div>
                </div>
                <div class="source-page-controls">
                    <button class="btn btn-sm btn-primary" onclick="configSourcePage('${sourcePage.sourceFileId}', ${sourcePage.sourcePageIndex}, ${index})">配置</button>
                    <button class="btn btn-sm btn-danger" onclick="removeSourcePage(${index})">删除</button>
                </div>
            </div>
        `;
    }).join('');
}

// 处理目标区域拖拽悬停
function handleTargetDragOver(event) {
    event.preventDefault();
    event.currentTarget.classList.add('drop-zone');
}

// 处理目标区域拖拽离开
function handleTargetDragLeave(event) {
    event.currentTarget.classList.remove('drop-zone');
}

// 处理目标区域拖拽放下
function handleTargetDrop(event, targetPageId) {
    event.preventDefault();
    event.currentTarget.classList.remove('drop-zone');
    
    try {
        const sourcePageData = JSON.parse(event.dataTransfer.getData('application/json'));
        addSourcePageToTarget(targetPageId, sourcePageData.fileId, sourcePageData.pageIndex);
    } catch (error) {
        console.error('处理拖拽数据失败:', error);
    }
    
    // 移除拖拽样式
    document.querySelectorAll('.dragging').forEach(item => {
        item.classList.remove('dragging');
    });
}

// 添加源页面到目标页面
function addSourcePageToTarget(targetPageId, fileId, pageIndex) {
    const targetPage = targetPages.find(tp => tp.id === targetPageId);
    if (!targetPage) return;
    
    const sourcePageConfig = {
        sourceFileId: fileId,
        sourcePageIndex: pageIndex,
        transform: {
            offsetX: 0,
            offsetY: 0,
            scaleX: 1.0,
            scaleY: 1.0,
            rotation: 0.0,
            cropX: 0.0,
            cropY: 0.0,
            cropWidth: 0,
            cropHeight: 0
        }
    };
    
    targetPage.sourcePages.push(sourcePageConfig);
    updateTargetPagesDisplay();
}

// 配置目标页面
function configTargetPage(targetPageId) {
    const targetPage = targetPages.find(tp => tp.id === targetPageId);
    if (!targetPage) return;
    
    currentConfigTarget = targetPage;
    
    // 填充当前配置
    document.getElementById('targetWidth').value = targetPage.widthMm;
    document.getElementById('targetHeight').value = targetPage.heightMm;
    
    // 重置变换配置
    document.getElementById('offsetX').value = 0;
    document.getElementById('offsetY').value = 0;
    document.getElementById('scaleX').value = 1;
    document.getElementById('scaleY').value = 1;
    document.getElementById('rotation').value = 0;
    document.getElementById('cropX').value = 0;
    document.getElementById('cropY').value = 0;
    document.getElementById('cropWidth').value = 0;
    document.getElementById('cropHeight').value = 0;
    
    document.getElementById('pageConfigModal').style.display = 'block';
}

// 应用页面配置
function applyPageConfig() {
    if (!currentConfigTarget) return;
    
    currentConfigTarget.widthMm = parseFloat(document.getElementById('targetWidth').value) || 210;
    currentConfigTarget.heightMm = parseFloat(document.getElementById('targetHeight').value) || 297;
    
    closeModal();
    updateTargetPagesDisplay();
}

// 关闭模态框
function closeModal() {
    document.getElementById('pageConfigModal').style.display = 'none';
    currentConfigTarget = null;
}

// 设置页面尺寸
function setPageSize(width, height) {
    if (currentConfigTarget) {
        document.getElementById('targetWidth').value = width;
        document.getElementById('targetHeight').value = height;
    }
}

// 删除文件
async function removeFile(fileId) {
    if (confirm('确定要删除这个文件吗？')) {
        try {
            await fetch(`/api/pdf/cache/${fileId}`, { method: 'DELETE' });
            uploadedFiles.delete(fileId);
            
            // 清理相关的PDF页面配置
            pdfPages.forEach(pdfPage => {
                pdfPage.elements = pdfPage.elements.filter(el => el.sourceFileId !== fileId);
            });
            
            updateUploadedFilesDisplay();
            updateSourcePagesDisplay();
            updatePdfPagesDisplay();
            updateCanvasDisplay();
            showMessage('文件删除成功', 'success');
        } catch (error) {
            console.error('删除文件失败:', error);
            showMessage('删除文件失败', 'error');
        }
    }
}

// 删除目标页面
function removeTargetPage(targetPageId) {
    if (confirm('确定要删除这个目标页面吗？')) {
        targetPages = targetPages.filter(tp => tp.id !== targetPageId);
        updateTargetPagesDisplay();
    }
}

// 删除源页面
function removeSourcePage(index) {
    if (currentConfigTarget) {
        currentConfigTarget.sourcePages.splice(index, 1);
        updateTargetPagesDisplay();
    }
}

// 处理画布页面拖拽悬停
function handleCanvasPageDragOver(event) {
    event.preventDefault();
    console.log('拖拽悬停事件触发'); // 调试信息
    const dropZone = event.currentTarget.querySelector('.canvas-page-drop-zone');
    if (dropZone) {
        dropZone.classList.add('drag-over');
    }
}

// 处理画布页面拖拽放下
function handleCanvasPageDrop(event, pageId) {
    event.preventDefault();
    event.stopPropagation();
    console.log('拖拽放下事件触发', pageId); // 调试信息
    
    const dropZone = event.currentTarget.querySelector('.canvas-page-drop-zone');
    if (dropZone) {
        dropZone.classList.remove('drag-over');
    }
    
    try {
        const sourcePageData = JSON.parse(event.dataTransfer.getData('application/json'));
        console.log('拖拽数据:', sourcePageData); // 调试信息
        
        // 计算放置位置（相对于画布的位置），使用当前缩放比例
        const currentScale = getCanvasScale();
        const canvasRect = event.currentTarget.getBoundingClientRect();
        const dropX = Math.max(0, (event.clientX - canvasRect.left) / currentScale); // 转换为实际毫米
        const dropY = Math.max(0, (event.clientY - canvasRect.top) / currentScale); // 转换为实际毫米
        
        console.log('放置位置:', dropX, dropY); // 调试信息
        addElementToCanvasPage(pageId, sourcePageData.fileId, sourcePageData.pageIndex, dropX, dropY);
    } catch (error) {
        console.error('处理拖拽数据失败:', error);
    }
    
    // 移除拖拽样式
    document.querySelectorAll('.dragging').forEach(item => {
        item.classList.remove('dragging');
    });
}

// 添加元素到画布页面
function addElementToCanvasPage(pageId, fileId, pageIndex, dropX = 10, dropY = 10) {
    if (!currentPdfPage || currentPdfPage.id !== pageId) return;
    
    // 获取源页面数据以确定实际尺寸
    const fileData = uploadedFiles.get(fileId);
    if (!fileData) return;
    
    const sourcePageData = fileData.pages[pageIndex];
    if (!sourcePageData) return;
    
    // 直接使用图片的原始宽高，不进行任何计算
    const originalWidth = sourcePageData.widthMm;
    const originalHeight = sourcePageData.heightMm;
    
    // 如果不允许重叠，寻找合适的位置
    const elementIndex = currentPdfPage.elements.length; // 新元素的索引
    const position = findNonOverlappingPosition(
        elementIndex, 
        Math.max(0, Math.min(dropX, currentPdfPage.widthMm - originalWidth)),
        Math.max(0, Math.min(dropY, currentPdfPage.heightMm - originalHeight)),
        originalWidth,
        originalHeight,
        0
    );
    
    const element = {
        sourceFileId: fileId,
        sourcePageIndex: pageIndex,
        sourcePageData: sourcePageData, // 存储源页面数据以便拖拽时使用
        transform: {
            offsetX: position.x,
            offsetY: position.y,
            scaleX: 1.0,
            scaleY: 1.0,
            rotation: 0.0,
            cropTop: 0.0,
            cropBottom: 0.0,
            cropLeft: 0.0,
            cropRight: 0.0,
            // 保留旧的裁切属性以兼容后端
            cropX: 0.0,
            cropY: 0.0,
            cropWidth: 0,
            cropHeight: 0
        }
    };
    
    currentPdfPage.elements.push(element);
    
    // 自动选择新添加的元素
    selectedCanvasElement = { elementIndex: currentPdfPage.elements.length - 1 };
    
    updateCanvasDisplay();
    updatePdfPagesDisplay();
    updateCurrentPageSettings();
    
    const positionInfo = (position.x !== dropX || position.y !== dropY) ? 
        ` (位置已调整为避免重叠)` : '';
    showMessage(`已添加 ${sourcePageData.fileName} 第${pageIndex + 1}页 (${Math.round(originalWidth)}×${Math.round(originalHeight)}mm)${positionInfo}`, 'success');
}

// 选择画布元素
function selectCanvasElement(elementIndex) {
    event.stopPropagation();
    selectedCanvasElement = { elementIndex };
    updateCanvasDisplay();
    updateCurrentPageSettings();
}

// 清除元素选择
function clearElementSelection() {
    if (selectedCanvasElement) {
        selectedCanvasElement = null;
        updateCanvasDisplay();
        updateCurrentPageSettings();
    }
}

// 计算旋转后元素的边界框
function getRotatedElementBounds(element) {
    const fileData = uploadedFiles.get(element.sourceFileId);
    const sourcePageData = fileData?.pages[element.sourcePageIndex];
    
    if (!sourcePageData) {
        return { minX: 0, maxX: 50, minY: 0, maxY: 50 };
    }
    
    // 计算裁切后的尺寸
    const cropLeft = element.transform.cropLeft || 0;
    const cropRight = element.transform.cropRight || 0;
    const cropTop = element.transform.cropTop || 0;
    const cropBottom = element.transform.cropBottom || 0;
    
    const croppedWidth = Math.max(0, sourcePageData.widthMm - cropLeft - cropRight);
    const croppedHeight = Math.max(0, sourcePageData.heightMm - cropTop - cropBottom);
    
    const width = croppedWidth * element.transform.scaleX;
    const height = croppedHeight * element.transform.scaleY;
    const rotation = element.transform.rotation * Math.PI / 180; // 转换为弧度
    
    // 计算旋转后的四个角点
    const corners = [
        { x: 0, y: 0 },           // 左上角
        { x: width, y: 0 },       // 右上角
        { x: width, y: height },  // 右下角
        { x: 0, y: height }       // 左下角
    ];
    
    // 应用旋转变换（以元素中心为旋转点）
    const centerX = width / 2;
    const centerY = height / 2;
    const cos = Math.cos(rotation);
    const sin = Math.sin(rotation);
    
    const rotatedCorners = corners.map(corner => {
        // 先平移到以中心为原点
        const x = corner.x - centerX;
        const y = corner.y - centerY;
        
        // 应用旋转
        const rotatedX = x * cos - y * sin;
        const rotatedY = x * sin + y * cos;
        
        // 平移回原来的位置
        return {
            x: rotatedX + centerX,
            y: rotatedY + centerY
        };
    });
    
    // 找出边界框
    const xs = rotatedCorners.map(p => p.x);
    const ys = rotatedCorners.map(p => p.y);
    
    return {
        minX: Math.min(...xs),
        maxX: Math.max(...xs),
        minY: Math.min(...ys),
        maxY: Math.max(...ys)
    };
}

// 开始拖拽元素
function startDragElement(event, elementIndex) {
    event.preventDefault();
    event.stopPropagation();
    
    if (!currentPdfPage) return;
    
    selectedCanvasElement = { elementIndex };
    updateCurrentPageSettings();
    
    const element = currentPdfPage.elements[elementIndex];
    const canvasRect = event.currentTarget.parentElement.getBoundingClientRect();
    
    const startX = event.clientX;
    const startY = event.clientY;
    const startOffsetX = element.transform.offsetX;
    const startOffsetY = element.transform.offsetY;
    
    function handleMouseMove(e) {
        const currentScale = getCanvasScale();
        const deltaX = (e.clientX - startX) / currentScale; // 转换为实际毫米
        const deltaY = (e.clientY - startY) / currentScale; // 转换为实际毫米
        
        // 计算期望的新位置
        let desiredX = startOffsetX + deltaX;
        let desiredY = startOffsetY + deltaY;
        
        // 获取元素的实际尺寸
        const fileData = uploadedFiles.get(element.sourceFileId);
        const sourcePageData = fileData?.pages[element.sourcePageIndex];
        
        if (sourcePageData) {
            const cropLeft = element.transform.cropLeft || 0;
            const cropRight = element.transform.cropRight || 0;
            const cropTop = element.transform.cropTop || 0;
            const cropBottom = element.transform.cropBottom || 0;
            
            const croppedWidth = Math.max(0, sourcePageData.widthMm - cropLeft - cropRight);
            const croppedHeight = Math.max(0, sourcePageData.heightMm - cropTop - cropBottom);
            
            const elementWidth = croppedWidth * element.transform.scaleX;
            const elementHeight = croppedHeight * element.transform.scaleY;
            
            let finalX = desiredX;
            let finalY = desiredY;
            
            // 推箱子碰撞检测 - 不允许重叠时
            if (!allowOverlap) {
                const currentX = element.transform.offsetX;
                const currentY = element.transform.offsetY;
                
                // 检查完整移动是否会重叠
                if (checkElementOverlap(elementIndex, desiredX, desiredY, elementWidth, elementHeight, element.transform.rotation)) {
                    // 如果会重叠，尝试只在X方向移动
                    const canMoveX = !checkElementOverlap(elementIndex, desiredX, currentY, elementWidth, elementHeight, element.transform.rotation);
                    // 尝试只在Y方向移动
                    const canMoveY = !checkElementOverlap(elementIndex, currentX, desiredY, elementWidth, elementHeight, element.transform.rotation);
                    
                    if (canMoveX && !canMoveY) {
                        // 只能在X方向移动
                        finalX = desiredX;
                        finalY = currentY;
                    } else if (!canMoveX && canMoveY) {
                        // 只能在Y方向移动
                        finalX = currentX;
                        finalY = desiredY;
                    } else if (!canMoveX && !canMoveY) {
                        // 两个方向都不能移动，保持原位
                        finalX = currentX;
                        finalY = currentY;
                    }
                    // 如果两个方向都能单独移动但组合移动会重叠，也保持原位
                    else if (canMoveX && canMoveY) {
                        finalX = currentX;
                        finalY = currentY;
                    }
                }
            }
            
            // 获取旋转后的边界框
            const bounds = getElementBounds(finalX, finalY, elementWidth, elementHeight, element.transform.rotation);
            
            // 应用画布边界限制
            element.transform.offsetX = Math.max(
                -bounds.minX + finalX,  // 确保左边不超出画布
                Math.min(
                    currentPdfPage.widthMm - bounds.maxX + finalX,  // 确保右边不超出画布
                    finalX
                )
            );
            element.transform.offsetY = Math.max(
                -bounds.minY + finalY,  // 确保上边不超出画布
                Math.min(
                    currentPdfPage.heightMm - bounds.maxY + finalY,  // 确保下边不超出画布
                    finalY
                )
            );
        }
        
        updateCanvasDisplay();
        updateCurrentPageSettings();
    }
    
    function handleMouseUp() {
        document.removeEventListener('mousemove', handleMouseMove);
        document.removeEventListener('mouseup', handleMouseUp);
    }
    
    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
}

// 更新元素变换
function updateElementTransform(property, value) {
    if (!selectedCanvasElement || !currentPdfPage) return;
    
    const element = currentPdfPage.elements[selectedCanvasElement.elementIndex];
    element.transform[property] = parseFloat(value) || 0;
    updateCanvasDisplay();
    
    // 如果修改的是裁切属性，需要更新设置面板显示的尺寸
    if (property.startsWith('crop')) {
        updateCurrentPageSettings();
    }
}

// 更新元素尺寸
function updateElementSize(dimension, value) {
    if (!selectedCanvasElement || !currentPdfPage) return;
    
    const element = currentPdfPage.elements[selectedCanvasElement.elementIndex];
    const fileData = uploadedFiles.get(element.sourceFileId);
    const sourcePageData = fileData?.pages[element.sourcePageIndex];
    
    if (!sourcePageData) return;
    
    const newValue = parseFloat(value) || 1;
    
    // 计算裁切后的原始尺寸
    const cropLeft = element.transform.cropLeft || 0;
    const cropRight = element.transform.cropRight || 0;
    const cropTop = element.transform.cropTop || 0;
    const cropBottom = element.transform.cropBottom || 0;
    
    const croppedWidth = Math.max(0.1, sourcePageData.widthMm - cropLeft - cropRight);
    const croppedHeight = Math.max(0.1, sourcePageData.heightMm - cropTop - cropBottom);
    
    if (dimension === 'width') {
        // 基于裁切后的宽度计算新的X缩放比例
        element.transform.scaleX = newValue / croppedWidth;
    } else if (dimension === 'height') {
        // 基于裁切后的高度计算新的Y缩放比例
        element.transform.scaleY = newValue / croppedHeight;
    }
    
    // 确保缩放比例在合理范围内
    element.transform.scaleX = Math.max(0.1, Math.min(10, element.transform.scaleX));
    element.transform.scaleY = Math.max(0.1, Math.min(10, element.transform.scaleY));
    
    updateCanvasDisplay();
    updateCurrentPageSettings(); // 更新显示的数值
}

// 删除选中的元素
function removeSelectedElement() {
    if (!selectedCanvasElement || !currentPdfPage) return;
    
    currentPdfPage.elements.splice(selectedCanvasElement.elementIndex, 1);
    selectedCanvasElement = null;
    updateCanvasDisplay();
    updatePdfPagesDisplay();
    updateCurrentPageSettings();
}

// 删除画布页面
function removeCanvasPage(pageId) {
    if (confirm('确定要删除这个页面吗？')) {
        canvasPages = canvasPages.filter(p => p.id !== pageId);
        if (currentCanvasPage && currentCanvasPage.id === pageId) {
            currentCanvasPage = canvasPages.length > 0 ? canvasPages[0] : null;
        }
        updateCanvasDisplay();
        updatePageSettings();
    }
}

// 清空画布
function clearCanvas() {
    if (canvasPages.length > 0 && confirm('确定要清空画布吗？')) {
        canvasPages = [];
        currentCanvasPage = null;
        selectedCanvasElement = null;
        updateCanvasDisplay();
        updatePageSettings();
    }
}

// 设置画布页面尺寸
function setCanvasPageSize(width, height) {
    document.getElementById('canvasWidth').value = width;
    document.getElementById('canvasHeight').value = height;
}

// 应用画布尺寸
function applyCanvasSize() {
    if (!currentCanvasPage) return;
    
    const width = parseFloat(document.getElementById('canvasWidth').value) || 210;
    const height = parseFloat(document.getElementById('canvasHeight').value) || 297;
    
    currentCanvasPage.widthMm = width;
    currentCanvasPage.heightMm = height;
    
    updateCanvasDisplay();
}

// 生成PDF
async function generatePdf() {
    if (pdfPages.length === 0) {
        showMessage('请先添加PDF页面', 'error');
        return;
    }
    
    const outputFileName = document.getElementById('outputFileName').value.trim() || 'merged';
    
    const request = {
        outputFileName: outputFileName,
        targetPages: pdfPages.map(page => ({
            widthMm: page.widthMm,
            heightMm: page.heightMm,
            sourcePages: page.elements.map(element => ({
                sourceFileId: element.sourceFileId,
                sourcePageIndex: element.sourcePageIndex,
                transform: element.transform
            }))
        }))
    };
    
    try {
        showLoading(true);
        
        const response = await fetch('/api/pdf/merge', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(request)
        });
        
        if (response.ok) {
            const blob = await response.blob();
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = outputFileName.endsWith('.pdf') ? outputFileName : outputFileName + '.pdf';
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
            
            showMessage('PDF生成成功！', 'success');
        } else {
            const error = await response.json();
            showMessage(`生成PDF失败: ${error.message}`, 'error');
        }
    } catch (error) {
        console.error('生成PDF失败:', error);
        showMessage('生成PDF失败', 'error');
    } finally {
        showLoading(false);
    }
}

// 清空所有
async function clearAll() {
    if (confirm('确定要清空所有内容吗？')) {
        try {
            await fetch('/api/pdf/cache', { method: 'DELETE' });
            uploadedFiles.clear();
            pdfPages = [];
            selectedSourcePage = null;
            selectedCanvasElement = null;
            currentPdfPage = null;
            
            updateUploadedFilesDisplay();
            updateSourcePagesDisplay();
            updatePdfPagesDisplay();
            updatePageCountDisplay();
            updateCanvasDisplay();
            updateCurrentPageSettings();
            
            showMessage('已清空所有内容', 'success');
        } catch (error) {
            console.error('清空失败:', error);
            showMessage('清空失败', 'error');
        }
    }
}

// 显示加载状态
function showLoading(show) {
    document.getElementById('loading').style.display = show ? 'block' : 'none';
}

// 显示消息
function showMessage(message, type = 'info') {
    // 创建消息元素
    const messageDiv = document.createElement('div');
    messageDiv.className = `message message-${type}`;
    messageDiv.textContent = message;
    
    // 添加样式
    messageDiv.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 20px;
        border-radius: 5px;
        color: white;
        font-weight: 500;
        z-index: 1000;
        max-width: 300px;
        word-wrap: break-word;
    `;
    
    // 根据类型设置颜色
    switch (type) {
        case 'success':
            messageDiv.style.backgroundColor = '#28a745';
            break;
        case 'error':
            messageDiv.style.backgroundColor = '#dc3545';
            break;
        case 'warning':
            messageDiv.style.backgroundColor = '#ffc107';
            messageDiv.style.color = '#333';
            break;
        default:
            messageDiv.style.backgroundColor = '#007bff';
    }
    
    // 添加到页面
    document.body.appendChild(messageDiv);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (messageDiv.parentNode) {
            messageDiv.parentNode.removeChild(messageDiv);
        }
    }, 3000);
}
